import {
	ref
} from "vue";
import useLoginTodo from "@/composition/useLoginTodo.js";

export default function useFollowAuthor(articleData, $http, store) {
	const isFollowAuthor = ref(false);

	// 初始化检查关注状态
	const initFollowStatus = () => {
		try {
			if (store.state.userInfo && store.state.userInfo.author_likes_ids && articleData.value?.author?.id) {
				const authorId = articleData.value.author.id;
				isFollowAuthor.value = store.state.userInfo.author_likes_ids.includes(authorId);
			}
		} catch (error) {
			console.error("初始化关注状态失败", error);
		}
	};

	// 切换关注状态
	const toggleFollowAuthor = async () => {
		try {
			// 检查用户是否登录
			const {
				checkedisLogin
			} = useLoginTodo(store.state.userInfo);
			const isLogin = await checkedisLogin();
			if (!isLogin) {
				return;
			}

			// 检查文章数据和作者信息
			if (!articleData || !articleData.value) {
				console.error('articleData对象不存在或为空');
				uni.showToast({
					title: '文章数据未加载完成',
					icon: 'none'
				});
				return;
			}
			if (!articleData.value.author || !articleData.value.author.id) {
				console.error('作者信息缺失:', articleData.value);
				uni.showToast({
					title: '无法获取作者信息',
					icon: 'none'
				});
				return;
			}

			// 获取作者ID
			const authorId = articleData.value.author.id;
			// 调用API切换关注状态
			const {
				returnMsg
			} = await $http.update_follow_author({
				userId: store.state.userInfo._id,
				authorId: authorId
			});
			if (returnMsg) {
				// 更新本地状态
				const newIsFollow = !isFollowAuthor.value;
				isFollowAuthor.value = newIsFollow;

				// 更新store中的用户信息
				const updatedUserInfo = {
					...store.state.userInfo,
					author_likes_ids: updateAuthorLikesIds(
						store.state.userInfo.author_likes_ids || [],
						authorId,
						newIsFollow
					)
				};
				// 调用mutation更新store
				store.commit('updateUserInfo', updatedUserInfo);

				// 显示提示信息
				uni.showToast({
					title: returnMsg || (newIsFollow ? '关注成功' : '取消关注成功'),
					icon: 'success'
				});
			} else {
				throw new Error(returnMsg || '操作失败');
			}
		} catch (error) {
			console.error("操作关注状态失败", error);
			uni.showToast({
				title: '操作失败',
				icon: 'none'
			});
		}
	};

	// 辅助函数：更新作者关注列表
	const updateAuthorLikesIds = (currentIds, authorId, isFollowing) => {
		const ids = [...currentIds];
		const index = ids.indexOf(authorId);

		if (isFollowing && index === -1) {
			// 添加关注
			ids.push(authorId);
		} else if (!isFollowing && index > -1) {
			// 取消关注
			ids.splice(index, 1);
		}

		return ids;
	};

	return {
		isFollowAuthor,
		toggleFollowAuthor,
		initFollowStatus
	};
}